<template>
    <div class="a-list" ref="doms">
        <div class="a-item" :class="item.cls" :style="item.style" v-for="(item, i) in alreadyExists" :key="item.uuid">
            <slot name="row" :row="item.origin" :ago="item.ago" :rowIndex="i">
                {{ item.ago }}
            </slot>
        </div>
        <JEmpty v-show="!alreadyExists.length"></JEmpty>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, computed, watch, toRaw } from "vue";

import { uuidCreate } from "@/comm/uuid";
import { formatTimeAgo, formatTimestamp } from "@/comm/format";
import { sleep, sortList } from "@/comm/tooler";
import { difference } from "@/comm/arrayTooler";
import JEmpty from "@/components/j-empty/index.vue";
// v-bind="$attrs"
type Item = {
    origin: any;
    timestamp: number;
    ago: string;
    uuid: string;
    cls: string;
    style: any;
};

const doms = ref();

const props = defineProps({
    list: {
        type: Array<any>,
        default: []
    },
    max: {
        type: Number,
        default: 6
    },
    interval: {
        type: Number,
        default: 1000
    }
});

// const alreadyExists = ref(getTopList(props.list));
const alreadyExists = ref<any[]>([]);
console.warn("alreadyExists", alreadyExists);
const waitingList = ref<any[]>([]);

function getTopList(ary: any[]) {
    let aim: Item[] = ary.map(i => wrapData(i));
    // console.log("yzt时间事件", aim);
    // aim.sort((a, b) => a.timestamp - b.timestamp );
    aim.reverse();
    return aim.slice(0, props.max);
}

// watch(() => [...props.list], (newVal, oldVal) => {
//     const diff = difference(newVal, oldVal);
//     waitingList.value = waitingList.value.concat(diff);
//     console.warn("总个数", oldVal.length, "--->", newVal.length, "wait", waitingList.value.length);
// })

let tid = 0;
let playing = false;
onMounted(() => {
    updateAnim();
});

onUnmounted(() => {
    window.clearTimeout(tid);
});

const stop = () => {
    window.clearTimeout(tid);
    // console.log("doms ------ ", doms.value);
};

const resetTable = (list: any[]) => {
    window.clearTimeout(tid);
    playing = false;
    alreadyExists.value = [];
    waitingList.value = [];
    setTimeout(() => {
        alreadyExists.value = getTopList(list);
        waitingList.value = list.slice(props.max);
        updateAnim();
        // console.warn(alreadyExists.value.length, "wait", waitingList.value.length);
    }, 60);
};

const addList = (list: any[]) => {
    // waitingList.value = waitingList.value.concat(list);
    const ary = waitingList.value.concat(list);
    waitingList.value = ary.sort((a, b) => (a.timestamp > b.timestamp ? -1 : 1));
};

defineExpose({
    stop,
    resetTable,
    addList,
    getList: () => alreadyExists.value
});

function updateAnim() {
    if (waitingList.value.length) {
        if (!playing) {
            addItem();
        }
    }

    // return;
    alreadyExists.value.forEach(i => (i.ago = formatTimeAgo(i.timestamp)));
    sortList(alreadyExists.value, "timestamp", true);
    tid = window.setTimeout(() => {
        updateAnim();
    }, props.interval);
}

function wrapData(item: any) {
    if (!item.timestamp) {
        item.timestamp = Date.now();
    }
    const timer1 = Math.floor(props.interval * 0.9);
    const timer2 = Math.floor(props.interval * 0.8);
    const obj: Item = {
        timestamp: item.timestamp,
        ago: formatTimeAgo(item.timestamp),
        uuid: item.uuid || uuidCreate(),
        origin: item,
        cls: "",
        style: {
            // transitionDuration: timer1 + "ms",
            // animationDuration: timer2 + "ms",
        }
    };
    return obj;
}

const addItem = async () => {
    const timer = Math.floor(props.interval * 0.8);
    playing = true;
    // let ary = [...alreadyExists.value];
    let ary = alreadyExists.value.map(item => toRaw(item)).sort((a, b) => a.timestamp + b.timestamp);
    // console.log("yzt__列表数据", ary);

    // ary.forEach(i => { i.cls = ''; i.style = {} });
    // await sleep(30);

    // ary.forEach(i => {
    //     i.cls = "has"
    // })
    let item = wrapData(waitingList.value.shift());
    // item.cls = "will";
    ary.unshift(item);
    alreadyExists.value = ary.slice(0, props.max);

    await sleep(60);

    // let num = getItemHeight();
    // alreadyExists.value.forEach(i => {
    //     if (i.cls == "has") {
    //         i.style = { ...i.style, transform: `translateY(${num}px)` };
    //     }
    // })

    // await sleep(timer);
    playing = false;
    // alreadyExists.value.forEach(i => {
    //     i.cls = "";
    //     i.style = {};
    // })
};

function getItemHeight() {
    if (!doms.value) return 0;
    let div = doms.value.querySelector(".a-item");
    if (!div) return 0;
    let num = div.clientHeight;
    return num;
}
</script>

<style lang="less" scoped>
@import url("./index.less");
</style>
